<?php
/**
 * This file contains support functions, for forms, persistant variables, and other purposes
 * 
 * The file contains a variety of support functions.  This included functions (helpers) for forms, and for persistance of variables.   All are just global functions.  Might split this up or
 * use namespaces in some future version.
 *
 * @package SupportFunctions
 *
 */
 
/**
 * make_array_select produces a single value select box from the passed array and parameters
 * 
 * 
 * @param array $valuesarray an array map of values, including values for the key and display for options to be created.  Each row should have a seperate entry.  
 * @param string $selectname The name of the select box
 * @param string $keyvalue The name of the map in valuesarray to show for the key (returned) value in the option.  example: $valuesarray[n][<keyvalue>] = 'id'
 * @param string $showvalue The name of the map in valuesarray to show for the displayed value in the option.  example: $valuesarray[n][<showvalue>] = 'name'
 * @param mixed $selectedvalue The value of the key that is selected for the drop down.
 * @param int $textlimit The maximum number of characters for the options.  Any chracters above will be truncated
 * @param array $opts Options array:  [id] = element id.  [onchangename]=name of change function (default: chg_<select name>)  [onchangeparam] = parameter for on change function
 *
 *
 */ 
function make_array_select($valuesarray, $selectname, $keyvalue,$showvalue,$selectedvalue, $textlimit = 40, $opts = '', $prelist = false) {
	if(isset($opts['id'])){
		$dd_id = $opts['id'];
	}
	else{
		$dd_id = $selectname;
	}
	
	if(isset($opts['onchangename'])){
		$onchangename = $opts['onchangename'];
		}
	else{
		$onchangename = "chg_$selectname";
		}
	
	if(isset($opts['rawformat'])){
		$rawformat = $opts['rawformat'];
	}	
	
	if(isset($opts['onchangeparam'])){
		$onchangeparam = $opts['onchangeparam'];
	}
		
	$atindex = 1;
	$dropdowntext .= "<SELECT name=\"";
	$dropdowntext .= $selectname;
	$dropdowntext .= "\" ";
	if(isset($opts['onchangename'])){
		$dropdowntext .= " onChange=\"";
		$dropdowntext .= $onchangename;
		$dropdowntext .= "\" ";
		}
	
	if(isset($opts['onchangeparam'])){
		$dropdowntext .= "($onchangeparam)\" ";
	}
	$dropdowntext .= " id=\"";
	$dropdowntext .= $dd_id;
	$dropdowntext .= "\"> \n";
		if (!empty($valuesarray)) {

		if($prelist){
		//print "Current Value is: $selectedvalue ";
			foreach ($prelist as $preentry){
			$dropdowntext.= "<OPTION value=\"" . $preentry['keyvalue'] . "\">".$preentry['showvalue'] . "</OPTION>\n";
			}
		}
		
			foreach ($valuesarray as $key=>$currentvalue) {
				//$currentvalue=$valuesarray[$atindex];
				$dropdowntext.= "<OPTION ";
				if ((string)$currentvalue[$keyvalue] == $selectedvalue) {
					$dropdowntext .= "selected=\"selected\" " ;
					}
				$dropdowntext.= "value=\"";
				$dropdowntext.=$currentvalue[$keyvalue];
				$dropdowntext.="\">";
				$dropdowntext.= substr($currentvalue[$showvalue],0,$textlimit);
				$dropdowntext.="</OPTION>\n";
				//$atindex++;
				}
			}
		$dropdowntext.= "</SELECT>";
	return $dropdowntext;
}



function make_array_radiogroup($valuesarray, $selectname, $showkey,$valuekey,$selectedvalue, $textlimit = 40, $opts = '', $prelist = false) {
	if(isset($opts['id'])){
		$dd_id = $opts['id'];
	}
	else{
		$dd_id = $selectname;
	}
	
	if(isset($opts['onchangename'])){
		$onchangename = $opts['onchangename'];
		}
	else{
		$onchangename = "chg_$selectname";
		}
	
	if(isset($opts['rawformat'])){
		$rawformat = $opts['rawformat'];
	}	
	
	if(isset($opts['onchangeparam'])){
		$onchangeparam = $opts['onchangeparam'];
	}
		
	$atindex = 1;

	if(isset($opts['onchangename'])){
		$onchange = " onChange=\"";
		$onchange .= $onchangename;
		$onchange .= "\"";
		}
	


		if (!empty($valuesarray)) {
		
		if($prelist){
			foreach ($prelist as $preentry){
			$dropdowntext.= "<input type='radio' name='$selectname' value='" .$preentry['keyvalue'];
			$dropdowntext .= "' $onchange  $rawformat >";
			$dropdowntext.= substr($currentvalue['showvalue'],0,$textlimit);
			$dropdowntext.="<br\>\n";
			}
		}		

			foreach ($valuesarray as $key=>$currentvalue) {
				//$currentvalue=$valuesarray[$atindex];
				//print "AT row $key Key = $currentvalue['keyvalue'] VALUE= $currentvalue['showvalue']
				$dropdowntext.= "<input type='radio' name='$selectname' "; 
				if ($currentvalue['keyvalue'] == $selectedvalue) {
					$dropdowntext .= " checked " ;
					}
				$dropdowntext.= "value=\"";
				$dropdowntext.=$currentvalue['keyvalue'];
				$dropdowntext.="\" $onchange  $rawformat >";
				$dropdowntext.= substr($currentvalue['showvalue'],0,$textlimit);
				$dropdowntext.="<br\>\n";
				//$atindex++;
				}
			}

	return $dropdowntext;
}

// THis function wil parce fields for CSV output.
// from http://www.wlscripting.com/tutorial/37
// Modified to use strstr instead of iregi, and added codes 10, 13 and 12 instead of newline
function csvEscapeText($comments) {
  $comments = str_replace('"', '""', $comments); // First off escape all " and make them ""
 // if(eregi(",", $comments) or eregi("\n", $comments) or eregi("\r", $comments)) { // Check if I have any commas or new lines
 if(strstr($comments, ",") or strstr($comments, 10)or strstr($comments, 13)or strstr($comments, 12)){
    return '"'.$comments.'"'; // If I have new lines or commas escape them
  } else {
    return $comments; // If no new lines or commas just return the value
  }
}
	/**
	 * GetPersistent will return a value for a variable name (varname)
     * The value will either come from  one of the server arrays (REQUEST, etc)
     * If a variable is not set in the server array, it will be the last value used, stored in the SESSION.
     * When values are recieved, they will be stored in the session.
     * By defalut, the $_REQUEST server array is used.  This can be set by the type {get, post, req}
     * @param string $varname The name of the variable as stored in the server arrays and SESSION
     * @param string $type The server arry to use {'get', 'post', 'req'} defaults to request
     * @param string $unsetvar The value for which the variable is to be unset on if it is the server array value.  defulats to '' (empty string)
	 */
function GetPersistent($varname,$type = 'req', $unsetval = ''){
if($type == 'get'){
	if(isset($_GET[$varname])){
			if($_GET[$varname] == $unsetvar){
				unset($_SESSION[$varname]);
				return NULL;
			} else{ // end got unsetvar
				$_SESSION[$varname] = $_GET[$varname];
				return $_GET[$varname];
			}
		} else { // end GET is set
			if(isset($_SESSION[$varname])){
				return $_SESSION[$varname];
			} else{ // end Session is set
				return NULL;
			}
		} // End GET not set
	} // end default type (Get)
else if($type == 'post'){
	if(isset($_POST[$varname])){
			if($_POST[$varname] == $unsetvar){
				unset($_SESSION[$varname]);
				return NULL;
			} else{ // end got unsetvar
				$_SESSION[$varname] = $_POST[$varname];
				return $_POST[$varname];
			}
		} else { // end POST is set
			if(isset($_SESSION[$varname])){
				return $_SESSION[$varname];
			} else{ // end Session is set
				return NULL;
			}
		} // End POST not set
	} // end type post
else{
		if(isset($_REQUEST[$varname])){
			if($_REQUEST[$varname] == $unsetvar){
				unset($_SESSION[$varname]);
				return NULL;
			} else{ // end got unsetvar
				$_SESSION[$varname] = $_REQUEST[$varname];
				return $_REQUEST[$varname];
			}
		} else { // end Request is set
			if(isset($_SESSION[$varname])){
				return $_SESSION[$varname];
			} else{ // end Session is set
				return NULL;
			}
		} // end default type (Request)
	}
}	

function GetPagePersistent($varname,$type = 'req', $unsetval = '', $page = 0){
	if($page === 0){
		$page = $_SERVER['PHP_SELF'];
	}

	if(isset($_REQUEST[$varname])){
		if($_REQUEST[$varname] == $unsetvar){
			unset($_SESSION[$page]['filters'][$varname]);
			return NULL;
		} else{ // end got unsetvar
			$_SESSION[$page]['filters'][$varname] = $_REQUEST[$varname];
			return $_REQUEST[$varname];
		}
	} else { // end Request is set
		if(isset($_SESSION[$page]['filters'][$varname])){
			return $_SESSION[$page]['filters'][$varname];
		} else{ // end Session is set
			return NULL;
		}
	} // end default type (Request)
}


/**
 * edit_field Method will make editable entry element for column
 * according to the feildspec[<column>][filter] specs
 * @param string $column Column to make input element for
 * @param string $elename Element Name 
 * @param string $changefunction is onChange, onBlur or onClick function
 * @param string $eleid = element id 
 * @param bool $prelist = Create first 'non selected' parameters.  Will output a drop-down with 3 values for a checklist.	 
 */
function MakeEditField($descriptor,$elename,$def_value, $changefunction ='', $eleid = '', $prelist = false, $top_dir = ''){
    $rawformat = $descriptor['rawformat'];
    // defaults for list key and value
    $showkey = 'showvalue';
    $valuekey = 'keyvalue';

    $size = '';
    $rows = '';

    if($descriptor['select'] == 'D'){
        $valuesarray = $descriptor['list'];
        if(isset($descriptor['showvalue'])){
            $showkey = $descriptor['showvalue'];
        }
        if(isset($descriptor['keyvalue'])){
            $valuekey = $descriptor['keyvalue'];
        }

        if(isset($descriptor['size'])){
            $boxsize = $descriptor['size'];
        }else{
			$boxsize = 40;
		}
		
		
        $dd_opts['id'] = $eleid;
        $dd_opts['onchangename'] = $changefunction;

        $select_text = make_array_select($valuesarray, $elename, $valuekey,$showkey,$def_value, $boxsize, $dd_opts, $prelist);
        $field .= "\n$select_text\n";

	}//end if select type 'D' for dropdown select
    // C for checkbox
    else if ($descriptor['select'] == 'C'){
        if(!$prelist){ // if we dont need a thrid 'neither' option, then make a checkbox
            $field .= "<input type='hidden' name='$elename' value='0' />";
            // NOTE:  the above hidden  this does not have an id, only a name, so that the javascript will not catch it using by_id, but the form processing will (using name)
            if($def_value != 0){
                $field .= "<input type='checkbox' name='$elename' id='$eleid' value='1' CHECKED $rawformat onClick=\"$changefunction\" />\n";
            }
            else {
                $field .= "<input type='checkbox' name='$elename' id='$eleid' value='1' $rawformat onClick=\"$changefunction\" />\n";
            }
        }// end no prelist
        else{ // make prelist
            $yesnoarray[1]['keyvalue'] = 0;
            $yesnoarray[1]['showvalue'] = 'No';
            $yesnoarray[2]['keyvalue'] = 1;
            $yesnoarray[2]['showvalue'] = 'Yes';

            $field = make_array_select($yesnoarray, $elename, 'keyvalue','showvalue',$def_value, 40, $dd_opts, $prelist);
        }
    }// end if checkbox type 'C'
    // R for radiobutton
    else if ($descriptor['select'] == 'R'){
        $valuesarray = $descriptor['list'];
        if(isset($descriptor['showvalue'])){
            $showkey = $descriptor['showvalue'];
        }
        if(isset($descriptor['keyvalue'])){
            $valuekey = $descriptor['keyvalue'];
        }
        $dd_opts['id'] = $eleid;
        $dd_opts['onchangename'] = $changefunction;

        $select_text = make_array_radiogroup($valuesarray, $elename, valuekey,$showkey,$$column, 40, $dd_opts, $noselect);
        $field .= "\n$select_text\n";
	}// end if radiobutton
    // T for textbox
    else if($descriptor['select'] == 'T'){
        $size = '';
        if(!empty($changefunction)){
            $blurparam = "onBlur = \"$changefunction\"";
        }
        if(!empty($descriptor['size'])){
            $size = " size='" . $descriptor['size'] . "'";
        }
        $field .= "<input type='text' name='$elename' $size id='$eleid' value='$def_value' $rawformat $blurparam />\n";
    }
    // A for textarea
    else if($descriptor['select'] == 'A'){
        if(!empty($changefunction)){
            $blurparam = "onBlur = \"$changefunction\"";
        }
        if(!empty($descriptor['size'])){
                $cols = " cols='" . $descriptor['size'] . "'";
                }
        if(!empty($descriptor['rows'])){
                $rows = " rows='" . $descriptor['rows'] . "'";
                }
        $field .= "<textarea name='$elename' id='$eleid' $cols $rows $blurparam >$def_value</textarea>\n";
    }
    else if ($descriptor['select']  == 'DT'){
            $size = " size='30' ";
            
			if(!empty($changefunction)){
				$blurparam = "onBlur = \"$changefunction\"";
			}else{
                $blurparam = "onBlur = \"donothing()\"";
                 }
            if(!empty($descriptor['size'])){
                    $size = " size='" . $descriptor['size'] . "'";
                    }
            (empty($descriptor['image']))?$calimg=$top_dir . "jscalendar/img.gif":$calimg=$descriptor['image'];
			$field .= "<input type='text' name='$elename' id='$eleid' value='$def_value' style='display:none;' $rawformat $blurparam />\n";
			//$field .= "<input type='text' name='$elename' id='$eleid' value='$def_value'  $rawformat $blurparam />\n";

            $field .= "<img src='" . $calimg . "' id='img_$eleid' />\n";
			if($prelist){
				$field .= "<input type='button' value='Clear' name='$elename' onclick=\"do_clearJScal(this,'$eleid')\"  />\n";
			}
            if(!empty($def_value)){
                $dateY = substr($def_value,0,4);
                $dateM = substr($def_value,5,2);
                $dateD = substr($def_value,8,2);
                $dateh = substr($def_value,11,2);
                $datei = substr($def_value,14,2);
                $dates = substr($def_value,17,2);
                //print "hour=$dateh, minute=$datei, second=$dates";
				//print "dateM $dateM dateY $dateY dated $dated";
                $intdate = mktime((int)$dateh,(int)$datei,(int)$dates,(int)$dateM,$dateD,$dateY);
                (empty($descriptor['showdateformat']))?$showdateformat="%B %d, %Y":$showdateformat=$descriptor['showdateformat'];
                $dateshow = strftime($showdateformat, $intdate);
              }

            $field .= "<input type='text' name='SD_$elename' $size id='SD_$eleid' value='$dateshow'  $rawformat onblur=\"do_JScalSet('SD_$eleid','$showdateformat','$eleid','%Y-%m-%d')\" />\n";
           $field .= "
<script type=\"text/javascript\">
Calendar.setup({
    ifFormat       :    \"";
    (!empty($descriptor['cal']['ifFormat']))?$field .= $descriptor['cal']['ifFormat']:$field .= "%Y-%m-%d";
    $field .= "\",      // format of the input field
    align          :    \"";
    (!empty($descriptor['cal']['align']))?$field .= $descriptor['cal']['align']:$field .= "T1";
    $field .= "\",           // alignment (defaults to Bl)
    showsTime      :    ";
    (!empty($descriptor['cal']['showsTime']))?$field .= $descriptor['cal']['showsTime']:$field .= "false";
    $field .= ",
    singleClick    :    ";
    (!empty($descriptor['cal']['singleClick']))?$field .= $descriptor['cal']['singleClick']:$field .= "true";
    $field .= ",
    onClose       :    setshowdate,
    inputField     :    \"$eleid\",     // id of the input field
    button         :    \"img_$eleid\"  // trigger for the calendar (button ID)
});
</script>
";
      }
    else if ($descriptor['select']  == 'CAL'){
            $size = " size='30' ";
            
			if(!empty($changefunction)){
				$blurparam = "onBlur = \"$changefunction\"";
			}else{
                $blurparam = "onBlur = \"donothing()\"";
                 }
            if(!empty($descriptor['size'])){
                    $size = " size='" . $descriptor['size'] . "'";
                    }
            (empty($descriptor['image']))?$calimg=$top_dir . "jscalendar/img.gif":$calimg=$descriptor['image'];
			$field .= "<input type='text' name='$elename' id='$eleid' value='$def_value' style='display:none;' $rawformat $blurparam />\n";
			//$field .= "<input type='text' name='$elename' id='$eleid' value='$def_value'  $rawformat $blurparam />\n";

            $field .= "<img src='" . $calimg . "' id='img_$eleid' />\n";
			if($prelist){
				$field .= "<input type='button' value='Clear' name='$elename' onclick=\"do_clearJScal(this,'$eleid')\"  />\n";
			}
            if(!empty($def_value)){
                $dateY = substr($def_value,0,4);
                $dateM = substr($def_value,5,2);
                $dateD = substr($def_value,8,2);
                $dateh = substr($def_value,11,2);
                $datei = substr($def_value,14,2);
                $dates = substr($def_value,17,2);
                //print "hour=$dateh, minute=$datei, second=$dates";
                $intdate = mktime((int)$dateh,(int)$datei,(int)$dates,$dateM,$dateD,$dateY);
                (empty($descriptor['showdateformat']))?$showdateformat="%B %d, %Y":$showdateformat=$descriptor['showdateformat'];
                $dateshow = strftime($showdateformat, $intdate);
              }

            $field .= "<span class='datespan' id='SD_$eleid' >$dateshow</span>\n";
           $field .= "
<script type=\"text/javascript\">
Calendar.setup({
    ifFormat       :    \"";
    (!empty($descriptor['cal']['ifFormat']))?$field .= $descriptor['cal']['ifFormat']:$field .= "%Y-%m-%d";
    $field .= "\",      // format of the input field
    daFormat       :    \"";
    (!empty($descriptor['cal']['daFormat']))?$field .= $descriptor['cal']['daFormat']:$field .= "%B %d, %Y";
    $field .= "\",      // format of the input field
    align          :    \"";
    (!empty($descriptor['cal']['align']))?$field .= $descriptor['cal']['align']:$field .= "T1";
    $field .= "\",           // alignment (defaults to Bl)
    showsTime      :    ";
    (!empty($descriptor['cal']['showsTime']))?$field .= $descriptor['cal']['showsTime']:$field .= "false";
    $field .= ",
    singleClick    :    ";
    (!empty($descriptor['cal']['singleClick']))?$field .= $descriptor['cal']['singleClick']:$field .= "true";
    $field .= ",
    onClose       :    calldateonblur,
    inputField     :    \"$eleid\",     // id of the input field
    displayArea     :    \"SD_$eleid\",     // id of the Display field	
    button         :    \"img_$eleid\"  // trigger for the calendar (button ID)
});
</script>
";
      }
    else if ($descriptor['select']  == 'MCAL'){
            $size = " size='30' ";
            
			if(!empty($changefunction)){
				$blurparam = "onBlur = \"$changefunction\"";
			}else{
                $blurparam = "onBlur = \"donothing()\"";
                 }
            if(!empty($descriptor['size'])){
                    $size = " size='" . $descriptor['size'] . "'";
                    }
            (empty($descriptor['image']))?$calimg=$top_dir . "jscalendar/img.gif":$calimg=$descriptor['image'];
			$field .= "<input type='text' name='$elename' id='$eleid' value='$def_value' style='display:none;' $rawformat $blurparam />\n";
			//$field .= "<input type='text' name='$elename' id='$eleid' value='$def_value'  $rawformat $blurparam />\n";

            $field .= "<img src='" . $calimg . "' id='img_$eleid' />\n";
			if($prelist){
				$field .= "<input type='button' value='Clear' name='$elename' onclick=\"do_clearJScal(this,'$eleid')\"  />\n";
			}
            if(!empty($def_value)){
                $dateY = substr($def_value,0,4);
                $dateM = substr($def_value,6,2);
                $dateD = substr($def_value,8,2);
                $dateh = substr($def_value,11,2);
                $datei = substr($def_value,14,2);
                $dates = substr($def_value,17,2);
                //print "hour=$dateh, minute=$datei, second=$dates";
                $intdate = mktime((int)$dateh,(int)$datei,(int)$dates,$dateM,$dateD,$dateY);
                (empty($descriptor['showdateformat']))?$showdateformat="%B %d, %Y":$showdateformat=$descriptor['showdateformat'];
                // may not need $dateshow, but leave in while creating others
				$dateshow = strftime($showdateformat, $intdate);
				$date_Y_show = strftime("%Y", $intdate);
				$date_m_show = strftime("%m", $intdate);
				$date_d_show = strftime("%d", $intdate);
				$date_H_show = strftime("%H", $intdate);
				$date_i_show = strftime("%i", $intdate);	
				$date_a_show = strftime("%a", $intdate);				
              }

	        $field .= "<span class='datespan' id='SD_$eleid' >$dateshow</span>\n";
			$field .= "<div class='hdmdate_y'>Year<input class='mdate_y' type='text' name='SD_Y_$elename' id='SD_Y_$eleid' value='$date_Y_show' onblur=\"SD_syncdate(this,'$eleid','Y')\" )";
			$field .= "<div class='hdmdate_m'>Month<input class='mdate_m' type='text' name='SD_m_$elename' id='SD_m_$eleid' value='$date_m_show' onblur=\"SD_syncdate(this,'$eleid','m')\" )></div>";
			$field .= "<div class='hdmdate_d'>Day<input type='text' class='mdate_d' name='SD_d_$elename' id='SD_d_$eleid' value='$date_d_show' onblur=\"SD_syncdate(this,'$eleid','d')\" )</div>";
			$field .= "<div class='hdmdate_y'>Hour<input type='text' class='mdate_y' name='SD_H_$elename' id='SD_H_$eleid' value='$date_H_show' onblur=\"SD_syncdate(this,'$eleid','H')\" )</div>";		   
			$field .= "<div class='hdmdate_i'>Minute<input type='text' class='mdate_i' name='SD_i_$elename' id='SD_i_$eleid' value='$date_i_show' onblur=\"SD_syncdate(this,'$eleid','i')\" )</div>";		   
			$field .= "<div class='hdmdate_a'>am/pm<input type='text' class='mdate_a' name='SD_a_$elename' id='SD_a_$eleid' value='$date_a_show' onblur=\"SD_syncdate(this,'$eleid','a')\" )</div>";
			
			$field .= "
<script type=\"text/javascript\">
Calendar.setup({
    ifFormat       :    \"";
    (!empty($descriptor['cal']['ifFormat']))?$field .= $descriptor['cal']['ifFormat']:$field .= "%Y-%m-%d";
    $field .= "\",      // format of the input field
    daFormat       :    \"";
    (!empty($descriptor['cal']['daFormat']))?$field .= $descriptor['cal']['daFormat']:$field .= "%B %d, %Y";
    $field .= "\",      // format of the input field
    align          :    \"";
    (!empty($descriptor['cal']['align']))?$field .= $descriptor['cal']['align']:$field .= "T1";
    $field .= "\",           // alignment (defaults to Bl)
    showsTime      :    ";
    (!empty($descriptor['cal']['showsTime']))?$field .= $descriptor['cal']['showsTime']:$field .= "false";
    $field .= ",
    singleClick    :    ";
    (!empty($descriptor['cal']['singleClick']))?$field .= $descriptor['cal']['singleClick']:$field .= "true";
    $field .= ",
    onClose       :    calldateonblur,
    inputField     :    \"$eleid\",     // id of the input field
    displayArea     :    \"SD_$eleid\",     // id of the Display field	
    button         :    \"img_$eleid\"  // trigger for the calendar (button ID)
});
</script>
";
      }	  
	  
	  

    return $field;
}


?>